import { showSection } from './utils.js';

// 加载用户列表
export async function loadUsers() {
    try {
        const response = await fetch('/api/users', {
            headers: {
                'Authorization': `Bearer ${localStorage.getItem('access_token')}`
            }
        });

        if (response.ok) {
            const users = await response.json();
            const tableBody = document.getElementById('users-table-body');
            tableBody.innerHTML = '';

            users.forEach(user => {
                const row = document.createElement('tr');
                row.innerHTML = `
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">${user.user_id}</td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">${user.username}</td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                        ${user.is_admin ? '<span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-green-100 text-green-800">是</span>' : '<span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-gray-100 text-gray-800">否</span>'}
                    </td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">${user.last_login || '从未登录'}</td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                        <button onclick="editUser('${user.user_id}')" class="text-blue-600 hover:text-blue-900 mr-3">编辑</button>
                        <button onclick="deleteUser('${user.user_id}')" class="text-red-600 hover:text-red-900">删除</button>
                    </td>
                `;
                tableBody.appendChild(row);
            });
        }
    } catch (error) {
        console.error('加载用户列表错误:', error);
    }
}

// 初始化用户管理
export function initUsers() {
    loadUsers();

    // 添加用户按钮事件
    document.getElementById('add-user-btn').addEventListener('click', function() {
        showUserModal('add');
    });

    // 保存用户按钮事件
    document.getElementById('save-user-btn').addEventListener('click', saveUser);

    // 取消按钮事件
    document.getElementById('cancel-user-btn').addEventListener('click', hideUserModal);
}

// 其他用户相关函数...